package jdbc2;

import org.junit.Test;

import java.sql.*;
import java.util.ArrayList;

/**
 * @Auther:lele
 * @Date:2025/3/12
 * 预编译
 */
public class MyDataManger {




    /**
     * 查找是否匹配
     * @throws Exception
     */
    @Test
    public void isAdmin() throws Exception {

         String admin="王五";
         String password="457777";
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ma?useSSL=false&serverTimezone=UTC", "root", "123456");
        String sql = "select * from user where admin=? and password=?";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
//        设置？的值
        preparedStatement.setString(1,admin);
        preparedStatement.setString(2,password);
        ResultSet resultSet = preparedStatement.executeQuery();

        if (resultSet.next()){
            System.out.println("登录成功");
        }else {
            System.out.println("用户名和密码有问题");
        }

    }

    /**
     * 查找全部数据
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public ArrayList<User> findAll() throws SQLException, ClassNotFoundException {

    ArrayList<User> users = new ArrayList<>();

    Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ma?useSSL=false&serverTimezone=UTC", "root", "123456");
        String sql = "select * from user";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);


        ResultSet resultSet = preparedStatement.executeQuery();
        while(resultSet.next()){
            String admin = resultSet.getString("admin");
            String password = resultSet.getString("password");
            System.out.println(admin+" "+password);

            User user = new User();
            user.setAdmin(admin);
            user.setPassword(password);
            users.add(user);

        }
    return users;




}

    /**
     * 添加数据
     * @throws Exception
     */
@Test
    public void addData() throws Exception{

        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ma?useSSL=false&serverTimezone=UTC", "root", "123456");
        String sql = "insert into user values (?,?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1,"abc");
        preparedStatement.setString(2,"123");
        preparedStatement.setInt(3,2333);

        int i = preparedStatement.executeUpdate();
        System.out.println("向数据库表中添加了"+i+"行数据");


    }

}
